﻿
"use strict";

var _layer_load_index = 0,showFlag = false;

chrome.runtime.onMessage.addListener(function(request, sender, sendRequest){
	if(request.type === "amazon-login-success"){
		loginAmazon(request);
	} else if(request.type === "amazon-show"){
		if(!showFlag) showLayer(request);
	} else if(request.type === "amazon-error"){
		layer.close(_layer_load_index);
		layer.alert(request.msg,{icon: 5});
	}
});

function loginAmazon(request){
	$("#ap_email").val(request.e);
	$("#ap_password").val(request.p);
	$('#signInSubmit').click();
}

function showLayer(request){
	showFlag = true;
	let shopName = request.name;
	let index = layer.open({
		type : 1,
		title: '亚马逊后台登录 -- ' + shopName,
		area : ['325px','260px'],
		btn  : ["登录"],
		content: '<div class="_amz_popup _laypop"><div>'+
					'<label class="label">帐号:</label>'+
					'<input type="text" name="acc" id="acc" placeholder="请输入工号@店铺">'+
				 '</div>'+
				 '<div >'+
					'<label class="label">密码:</label>'+
					'<input type="password" name="password" id="pwd">'+
				 '</div>'+
				 '<div >'+
				 	'<label class="label">店铺:</label>'+
				 	'<span>'+shopName+'</span>'+
				   '</div></div>',
		success : function(layero, index){
					document.onkeydown = function(e){
						let ev = document.all ? window.event : e;
						if(ev.keyCode==13) {
							loginVerify(shopName,layero);
						}
					}
				  },
		yes : function(index,layero){
			loginVerify(shopName,layero);
		}
	  });
}

function loginVerify(shopName,layero){
	let acc = $("#acc",$(layero)).val();
	let pwd = $("#pwd",$(layero)).val();

	if(acc==''||pwd==''){
		layer.alert("帐号密码不能为空",{icon: 5});
		return;
	}

	let arr = acc.split("@");
	if(! (arr[1] && arr[1].trim().toUpperCase() === shopName) ){
		layer.alert("登录店铺错误",{icon: 5});
		return;
	}
	
	let msg = {
		acc:arr[0],
		pwd:pwd,
		shop:shopName,
		type:"amazon-login"
	}

	_layer_load_index = layer.load(1, {
		shade: [0.1,'#fff'] 
	});
	chrome.runtime.sendMessage(msg);
}

$(function(){
	$("#ap_signin_form").hide();
	$("#ap_email").attr("type","hidden").val("");
	$("#ap_password").attr("type","hidden").val("");

	if($("#message_error").hasClass("error")){
		let msg = $("#message_error > p").text().trim();
		layer.alert(msg,{icon: 2,zIndex:1989101400});
	}
});

//'chrome-extension://__MSG_@@extension_id__/image.png'